<template>
  <div>
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="物资类型">
          <el-select v-model="searchForm.typeId" placeholder="请选择物资类型" clearable style="width: 200px;">
            <el-option
                v-for="item in typeOptions"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 操作按钮 -->
    <div class="action-bar">
      <el-button type="success" @click="handleAddMaterial">新增物资</el-button>
    </div>

    <!-- 物资表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="materialId" label="物资ID" width="80"/>
      <el-table-column prop="name" label="物资名称"/>
      <el-table-column prop="description" label="描述" show-overflow-tooltip/>
      <el-table-column prop="quantity" label="数量" width="100"/>
      <el-table-column prop="typeName" label="类型" width="120"/>
<!--      <el-table-column prop="status" label="状态" width="100">-->
<!--        <template #default="scope">-->
<!--          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'">-->
<!--            {{ scope.row.status === 1 ? '可用' : '不可用' }}-->
<!--          </el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column prop="createTime" label="创建时间" width="180"/>
      <el-table-column label="操作" width="250">
        <template #default="scope">
          <el-button type="primary" size="small" @click="handleEditMaterial(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDeleteMaterial(scope.row.materialId)">删除</el-button>
          <el-button type="info" size="small" @click="handleViewDetails(scope.row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination">
      <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>

    <!-- 新增/编辑物资对话框 -->
    <el-dialog :title="dialogTitle" v-model="dialogVisible" width="40%">
      <el-form :model="currentForm" :rules="rules" ref="materialFormRef">
        <el-form-item label="物资名称" prop="name">
          <el-input v-model="currentForm.name" placeholder="请输入物资名称"/>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" v-model="currentForm.description" placeholder="请输入物资描述"/>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="currentForm.quantity" :min="0" placeholder="请输入数量"/>
        </el-form-item>
        <el-form-item label="物资类型" prop="typeId">
          <el-select v-model="currentForm.typeId" placeholder="请选择物资类型">
            <el-option
                v-for="item in typeOptions"
                :key="item.typeId"
                :label="item.typeName"
                :value="item.typeId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="currentForm.status" placeholder="请选择状态">
            <el-option :value="1" label="可用"/>
            <el-option :value="0" label="不可用"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 物资详情对话框 -->
    <el-dialog title="物资详情" v-model="detailsDialogVisible" width="80%">
      <el-tabs v-model="activeTab">
        <!-- 申请记录标签页 -->
        <el-tab-pane label="申请记录" name="requests">
          <el-table :data="requestList" border style="width: 100%;">
            <el-table-column prop="requestId" label="申请ID" width="80"/>
            <el-table-column prop="username" label="申请人"/>
            <el-table-column prop="phone" label="联系电话"/>
            <el-table-column prop="materialVo.name" label="物资名称"/>
            <el-table-column prop="requestQuantity" label="申请数量" width="100"/>
            <el-table-column prop="requestTime" label="申请时间" width="180"/>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ getStatusText(scope.row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button
                  v-if="scope.row.status === 0"
                  type="success"
                  size="small"
                  @click="handleApproveRequest(scope.row.requestId)"
                >批准</el-button>
                <el-button
                  v-if="scope.row.status === 0"
                  type="danger"
                  size="small"
                  @click="handleRejectRequest(scope.row.requestId)"
                >拒绝</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
                v-model:current-page="requestCurrentPage"
                :page-size="requestPageSize"
                :total="requestTotal"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleRequestSizeChange"
                @current-change="handleRequestCurrentChange"
            />
          </div>
        </el-tab-pane>

        <!-- 捐赠记录标签页 -->
        <el-tab-pane label="捐赠记录" name="donations">
          <el-table :data="donationList" border style="width: 100%;">
            <el-table-column prop="donationRecord.donationId" label="捐赠ID" width="80"/>
            <el-table-column prop="user.username" label="捐赠人"/>
            <el-table-column prop="user.phone" label="联系电话"/>
            <el-table-column prop="material.name" label="物资名称"/>
            <el-table-column prop="donationRecord.donationNumber" label="捐赠数量" width="100"/>
            <el-table-column prop="donationRecord.donationTime" label="捐赠时间" width="180"/>
            <el-table-column prop="donationRecord.status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getStatusType(scope.row.donationRecord.status)">
                  {{ getStatusText(scope.row.donationRecord.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200">
              <template #default="scope">
                <el-button
                  v-if="scope.row.donationRecord.status === 0"
                  type="success"
                  size="small"
                  @click="handleApproveDonation(scope.row.donationRecord.donationId)"
                >批准</el-button>
                <el-button
                  v-if="scope.row.donationRecord.status === 0"
                  type="danger"
                  size="small"
                  @click="handleRejectDonation(scope.row.donationRecord.donationId)"
                >拒绝</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination">
            <el-pagination
                v-model:current-page="donationCurrentPage"
                :page-size="donationPageSize"
                :total="donationTotal"
                :page-sizes="[10, 20, 30, 50]"
                layout="total, sizes, prev, pager, next, jumper"
                @size-change="handleDonationSizeChange"
                @current-change="handleDonationCurrentChange"
            />
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import {ElMessage, ElMessageBox} from 'element-plus';
import {
  materialDeleteOne,
  materialInsertOne,
  materialSelectPage,
  materialUpdateOne,
  requestSelectPage,
  requestUpdateStatus,
  donationSelectPage,
  donationUpdateStatus, videoTypeSelectList
} from "@/api/material.js";

// 表格数据
const tableData = ref([]);
const total = ref(0);
const currentPage = ref(1);
const pageSize = ref(10);

// 物资类型选项
const typeOptions = ref([]);

// 搜索条件
const searchForm = reactive({
  typeId: null,
});

// 对话框相关
const dialogVisible = ref(false);
const dialogTitle = ref('');
const currentForm = reactive({
  materialId: null,
  name: '',
  description: '',
  quantity: 0,
  typeId: null,
  status: 1,
});
const materialFormRef = ref(null);

// 验证规则
const rules = {
  name: [
    {required: true, message: '物资名称不能为空', trigger: 'blur'},
    {min: 2, max: 50, message: '物资名称长度在2到50个字符之间', trigger: 'blur'}
  ],
  description: [
    {required: true, message: '描述不能为空', trigger: 'blur'},
    {min: 10, message: '描述长度不能少于10个字符', trigger: 'blur'}
  ],
  quantity: [
    {required: true, message: '数量不能为空', trigger: 'blur'}
  ],
  typeId: [
    {required: true, message: '请选择物资类型', trigger: 'change'}
  ],
  status: [
    {required: true, message: '请选择状态', trigger: 'change'}
  ],
};

// 申请记录相关
const requestDialogVisible = ref(false);
const requestList = ref([]);
const requestTotal = ref(0);
const requestCurrentPage = ref(1);
const requestPageSize = ref(10);

// 捐赠记录相关
const donationDialogVisible = ref(false);
const donationList = ref([]);
const donationTotal = ref(0);
const donationCurrentPage = ref(1);
const donationPageSize = ref(10);

// 物资详情对话框相关
const detailsDialogVisible = ref(false);
const activeTab = ref('requests');
const currentMaterialId = ref(null);

// 获取物资类型列表
const fetchMaterialTypes = async () => {
  try {
    const response = await videoTypeSelectList();
    typeOptions.value = response.data.records;
  } catch (error) {
    ElMessage.error('获取物资类型列表失败');
  }
};

// 获取物资列表
const fetchMaterials = async () => {
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value,
      typeId: searchForm.typeId
    };
    if (!params.typeId) {
      delete params.typeId;
    }
    const response = await materialSelectPage(params);
    tableData.value = response.data.records;
    total.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取物资列表失败');
  }
};

// 新增物资
const handleAddMaterial = () => {
  dialogTitle.value = '新增物资';
  dialogVisible.value = true;
  resetForm();
};

// 编辑物资
const handleEditMaterial = (row) => {
  dialogTitle.value = '编辑物资';
  dialogVisible.value = true;
  Object.assign(currentForm, row);
};

// 删除物资
const handleDeleteMaterial = (materialId) => {
  ElMessageBox.confirm('确认删除该物资?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await materialDeleteOne(materialId);
      ElMessage.success('删除成功');
      await fetchMaterials();
    } catch (error) {
      ElMessage.error('删除失败');
    }
  });
};

// 保存物资（新增/编辑）
const handleSubmit = () => {
  materialFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (currentForm.materialId) {
          // 编辑
          await materialUpdateOne(currentForm);
        } else {
          // 新增
          await materialInsertOne(currentForm)
        }
        ElMessage.success('保存成功');
        dialogVisible.value = false;
        await fetchMaterials();
      } catch (error) {
        ElMessage.error('保存失败');
      }
    }
  });
};

// 分页事件
const handleSizeChange = (size) => {
  pageSize.value = size;
  fetchMaterials();
};

const handleCurrentChange = (page) => {
  currentPage.value = page;
  fetchMaterials();
};

// 搜索
const handleSearch = () => {
  currentPage.value = 1;
  fetchMaterials();
};

// 重置搜索
const resetSearch = () => {
  currentPage.value = 1;
  searchForm.typeId = null;
  fetchMaterials();
};

// 重置表单
const resetForm = () => {
  Object.assign(currentForm, {
    materialId: null,
    name: '',
    description: '',
    quantity: 0,
    typeId: null,
    status: 1,
  });
  materialFormRef.value?.clearValidate();
};

// 获取申请记录
const fetchRequests = async () => {
  try {
    const params = {
      page: requestCurrentPage.value,
      size: requestPageSize.value,
      materialId: currentMaterialId.value
    };
    const response = await requestSelectPage(params);
    requestList.value = response.data.records;
    requestTotal.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取申请记录失败');
  }
};

// 获取捐赠记录
const fetchDonations = async () => {
  try {
    const params = {
      page: donationCurrentPage.value,
      size: donationPageSize.value,
      materialId: currentMaterialId.value
    };
    const response = await donationSelectPage(params);
    donationList.value = response.data.records;
    donationTotal.value = response.data.total;
  } catch (error) {
    ElMessage.error('获取捐赠记录失败');
  }
};

// 申请记录分页事件
const handleRequestSizeChange = (size) => {
  requestPageSize.value = size;
  fetchRequests();
};

const handleRequestCurrentChange = (page) => {
  requestCurrentPage.value = page;
  fetchRequests();
};

// 捐赠记录分页事件
const handleDonationSizeChange = (size) => {
  donationPageSize.value = size;
  fetchDonations();
};

const handleDonationCurrentChange = (page) => {
  donationCurrentPage.value = page;
  fetchDonations();
};

// 状态相关方法
const getStatusType = (status) => {
  switch (status) {
    case 0:
      return 'warning';
    case 1:
      return 'success';
    case 2:
      return 'danger';
    default:
      return 'info';
  }
};

const getStatusText = (status) => {
  switch (status) {
    case 0:
      return '待审核';
    case 1:
      return '已批准';
    case 2:
      return '已拒绝';
    default:
      return '未知';
  }
};

// 处理申请状态
const handleApproveRequest = (requestId) => {
  ElMessageBox.confirm('确认批准该申请?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await requestUpdateStatus(requestId, 1);
      ElMessage.success('批准成功');
      await fetchRequests();
    } catch (error) {
      ElMessage.error('批准失败');
    }
  });
};

const handleRejectRequest = (requestId) => {
  ElMessageBox.confirm('确认拒绝该申请?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await requestUpdateStatus(requestId, 2);
      ElMessage.success('拒绝成功');
      await fetchRequests();
    } catch (error) {
      ElMessage.error('拒绝失败');
    }
  });
};

// 处理捐赠状态
const handleApproveDonation = (donationId) => {
  ElMessageBox.confirm('确认批准该捐赠?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await donationUpdateStatus(donationId, 1);
      ElMessage.success('批准成功');
      await fetchDonations();
    } catch (error) {
      ElMessage.error('批准失败');
    }
  });
};

const handleRejectDonation = (donationId) => {
  ElMessageBox.confirm('确认拒绝该捐赠?', '提示', {
    type: 'warning',
  }).then(async () => {
    try {
      await donationUpdateStatus(donationId, 2);
      ElMessage.success('拒绝成功');
      await fetchDonations();
    } catch (error) {
      ElMessage.error('拒绝失败');
    }
  });
};

// 查看详情
const handleViewDetails = (row) => {
  currentMaterialId.value = row.materialId;
  detailsDialogVisible.value = true;
  activeTab.value = 'requests';
  // 加载申请记录
  requestCurrentPage.value = 1;
  fetchRequests();
  // 加载捐赠记录
  donationCurrentPage.value = 1;
  fetchDonations();
};

// 初始化数据
onMounted(() => {
  fetchMaterialTypes();
  fetchMaterials();
});
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}

.action-bar {
  margin-bottom: 15px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}
</style>
